<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'

const userStore = useUserStore()
const router = useRouter()
const cartStore = useCartStore()

// 登录状态判断
const isLoggedIn = computed(() => !!userStore.userInfo?.token)

// 退出登录操作
const handleLogout = async () => {
  try {
    // 清除用户信息
    userStore.clearUserInfo()
    cartStore.clearCartlist()
    // 跳转到登录页
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
  }
}
</script>

<template>
  <nav class="app-topnav" aria-label="顶部导航">
    <div class="container">
      <ul>
        <!-- 已登录状态 -->
        <template v-if="isLoggedIn">
          <li><router-link to="/member"><i class="iconfont icon-user"></i>{{ userStore.userInfo.account }}</router-link></li>
          <li>
            <el-popconfirm
              title="确认退出吗?"
              @confirm="handleLogout"
              confirm-button-text="确认"
              cancel-button-text="取消"
              aria-label="退出登录确认"
            >
              <template #reference>
                <a href="#" aria-label="退出登录">退出登录</a>
              </template>
            </el-popconfirm>
          </li>
          <li><router-link to="/member/order">我的订单</router-link></li>
          <li><router-link to="/member">会员中心</router-link></li>
        </template>
        <!-- 未登录状态 -->
        <template v-else>
          <li><router-link to="/login">请先登录</router-link></li>
          <li><router-link to="/help">帮助中心</router-link></li>
          <li><router-link to="/about">关于我们</router-link></li>
        </template>
      </ul>
    </div>
  </nav>
</template>

<style scoped lang="scss">
.app-topnav {
  background: #333;

  ul {
    display: flex;
    height: 53px;
    justify-content: flex-end;
    align-items: center;
    list-style: none;
    margin: 0;
    padding: 0;

    li {
      & > a,
      & > router-link {
        padding: 0 15px;
        color: #cdcdcd;
        line-height: 1;
        display: inline-block;
        text-decoration: none;
        transition: color 0.3s ease;

        i {
          font-size: 14px;
          margin-right: 2px;
        }

        &:hover {
          color: $xtxColor;
        }
      }

      // 第一个li之后的所有li添加左边框
      + li {
        & > a,
        & > router-link {
          border-left: 2px solid #666;
        }
      }
    }
  }
}
</style>
